//传入路径（四种类型）
//返回值是文件id，-1表示非法路径

#include "../include/server.h"

int parsePath(char *filePath, int curDirID, int ownerID, char *md5str, char *type){
    //===========所需变量============
    int fileID = 0;
    char *buf = filePath;
    char names[20][20];
    memset(names, 0, 400);
    int cnt = 0;
    int i = 0;

    // >>>>>>>> 1、把路径拆分，分别存到数组中<<<<<<<<
    char *token = strsep(&buf, "/");
    while(token != NULL){
        memcpy(names[cnt++], token, strlen(token));
        token = strsep(&buf, "/");
    }
    // 根据第一个路径名确定path的类型
    if(strcmp(names[0], "") == 0){
        //filepath是绝对路径
        curDirID = 0;
        ++i;
    }
    else if(strcmp(names[0], "..") == 0){
        //路径从上一级目录开始
        curDirID = query_parentID(curDirID, ownerID);
        if(-1 == curDirID){
            //非法路径
            return -1;
        }
    }
    else if(strcmp(names[0], ".") == 0){
        //path从当前路径开始
        ++i;
    }
    else{}
    //path从当前目录开始，不用修改
    /* printf("names[%d] = %s\n", i, names[i]); */
    
    // >>>>>>>> 2、连接数据库<<<<<<<<<<<
    
    MYSQL *conn;
    char *server = "localhost";
    char *user = "root";
    char *password = "1234";
    char *database = "netdisk";//要访问的数据库名称

    //初始化
    conn = mysql_init(NULL);
    if(!conn)
    {
        printf("MySQL init failed\n");
        return -1;
    }

    //连接数据库，看连接是否成功，只有成功才能进行后面的操作
    if(!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0))
    {
        printf("Error connecting to database: %s\n", mysql_error(conn));
        return -1;
    }
    else
    {
        /* printf("MySQL Connected...\n"); */
    }

    // >>>>>>>> 3、获取最终的fileID<<<<<<<<<<<
    int ret = 0;
    for(; i < cnt; ++i){
        /* printf("name = %s\n", names[i]); */
        ret = query_childID(conn, curDirID, names[i], ownerID, md5str, type);
        /* printf("fileID = %d, type = %c\n", ret, *type); */
        if(*type == 'f' || ret == -1){
            ++i;
            break;
        }
    }
    if(i < cnt || ret == -1){
        //path中间有非法路径
        printf("illeagl path!\n");
        return -1;
    }
    return ret;
}

int query_childID(MYSQL *conn, int curDirID, char *filename, int ownerID, char *md5str, char *type){
    //查询数据库，返回文件的id

    //1、拼接查询语句
    char query[300] = {0};
    char buf[100] = "select id,md5,type from file where parent_id=";
    unsigned int queryRet;
    //将搜索语句拼接起来
    sprintf(query, "%s%d and owner_id=%d and filename='%s'", buf, curDirID, ownerID, filename);

    //在输出前先打印查询语句
    /* puts(query); */
    
    //===========所需变量============
    MYSQL_RES *res;
    MYSQL_ROW row;
    int fileID = 0;

    //2、查询，拼接path，返回parentID
    queryRet = mysql_query(conn, query);
    if(queryRet){
        printf("Error making query: %s\n", mysql_error(conn));
        return -1;
    }
    else{
        //用mysql_num_rows可以得到查询的结果集有几行
        //要配合mysql_store_result使用
        //第一种判断方式
        res = mysql_store_result(conn);
        /* printf("mysql_num_rows = %lu\n", (unsigned long)mysql_num_rows(res)); */

        //第二种判断方式,两种方式不能一起使用
		/* res = mysql_use_result(conn); */
            
        row = mysql_fetch_row(res);
		if(NULL == row)
        {
            //如果传入的文件名不在file表中，返回0
            printf("Don't find any data\n");
            return -1;
        }
        else{
            //查询成功，获取
            fileID = atoi(row[queryRet++]);
            memset(md5str, 0, 128);
            memcpy(md5str, row[queryRet], strlen(row[queryRet]));
            ++queryRet;
            *type = *row[queryRet];
            /* printf("fileID = %d, type = %c\n", fileID, *type); */
            /* printf("md5str = %s\n", md5str); */
            return fileID;
        }

    }
    /* return fileID; */
}
